<!-- templates/categories/categorylist.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>类别管理 - 商店进销存管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 从 unpkg CDN 引入 ECharts -->
  <script src="https://unpkg.com/echarts@5.4.0/dist/echarts.min.js"></script>

  <!-- 引入 Toastify CSS 和 JS -->
  <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#0FC6C2',
            success: '#00B42A',
            warning: '#FF7D00',
            danger: '#F53F3F',
            info: '#86909C'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }

      .sidebar-item {
        @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
      }

      .sidebar-item.active {
        @apply bg-primary/10 text-primary border-l-4 border-primary;
      }

      .card-shadow {
        @apply shadow-md hover:shadow-lg transition-shadow duration-300;
      }
      .echart-container {
        width: 100%;
        height: 350px; /* 初始高度，可根据需求调整 */
      }
    }
  </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
  <div class="container mx-auto px-4 py-3 flex justify-between items-center">
    <div class="flex items-center space-x-2">
      <i class="fa fa-cubes text-primary text-2xl"></i>
      <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
    </div>

    <div class="flex items-center space-x-6">
      <div class="relative">
        <input type="text" placeholder="搜索..."
               class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
      </div>

      <div class="flex items-center space-x-4">
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-bell-o text-xl"></i>
        </button>
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-cog text-xl"></i>
        </button>
        <div class="flex items-center space-x-2 cursor-pointer">
          <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
          <span class="text-gray-700">管理员</span>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="flex flex-1 overflow-hidden">
  <!-- 侧边栏导航 -->
  <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
    <nav class="py-4">
      <div class="px-4 mb-4">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
      </div>

      <a href="index.html" class="sidebar-item" data-path="index.html">
        <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
        <span>仪表盘</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
      </div>

      <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
        <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
        <span>商品管理</span>
      </a>

      <a href="categorylist.html" class="sidebar-item active" data-path="categorylist.html">
        <i class="fa fa-th-large w-5 h-5 mr-3"></i>
        <span>类别管理</span>
      </a>

      <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
        <i class="fa fa-truck w-5 h-5 mr-3"></i>
        <span>供应商管理</span>
      </a>


      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
      </div>

      <a href="warehouselist.html" class="sidebar-item"data-path="warehouselist.html">
        <i class="fa fa-archive w-5 h-5 mr-3"></i>
        <span>仓库管理</span>
      </a>

      <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
        <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
        <span>库存查询</span>
      </a>

      <a href="instock.html" class="sidebar-item" data-path="instock.html">
        <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
        <span>入库管理</span>
      </a>

      <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
        <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
        <span>出库管理</span>
      </a>

      <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
        <i class="fa fa-exchange w-5 h-5 mr-3"></i>
        <span>转仓管理</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
      </div>

      <a href="../statistics/sales.html" class="sidebar-item">
        <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
        <span>销售统计</span>
      </a>

      <a href="../statistics/inventory.html" class="sidebar-item">
        <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
        <span>库存分析</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
      </div>

      <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
        <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
        <span>用户管理</span>
      </a>

      <a href="backup.html" class="sidebar-item" data-path="backup.html">
        <i class="fa fa-history w-5 h-5 mr-3"></i>
        <span>数据库备份与恢复</span>
      </a>
    </nav>
  </aside>

  <!-- 主内容区域 -->
  <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
    <div class="container mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">类别管理</h2>
        <p class="text-gray-500 mt-1">管理商店的所有商品类别</p>
      </div>

      <!-- 操作按钮 -->
      <div class="mb-4 flex justify-between items-center">
        <button class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center" id="addCategoryBtn">
          <i class="fa fa-plus mr-2"></i> 添加类别
        </button>
        <div class="flex space-x-2">
          <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200" id="filterBtn">
            <i class="fa fa-filter mr-1"></i> 筛选
          </button>
          <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200">
            <i class="fa fa-download mr-1"></i> 导出
          </button>
        </div>
      </div>

      <!-- 筛选表单 -->
      <div id="filterForm" class="mb-4 bg-white rounded-lg p-4 card-shadow hidden">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">类别名称</label>
            <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入类别名称">
          </div>
          <div class="flex items-end space-x-2">
            <button id="applyFilterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
              <i class="fa fa-search mr-2"></i> 搜索
            </button>
            <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- 类别列表 -->
      <div class="bg-white rounded-xl p-6 card-shadow">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead>
            <tr class="border-b border-gray-200">
              <th class="py-3 text-left text-sm font-medium text-gray-500">类别ID</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">类别名称</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">商品数量</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
            </tr>
            </thead>
            <tbody id="categoryTable">
            <!-- 数据将通过JS动态渲染 -->
            <tr>
              <td colspan="4" class="py-4 text-center">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                <p class="mt-2 text-gray-600">加载类别数据中...</p>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件 -->
        <div class="mt-6 flex justify-between items-center">
          <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
          <div class="flex space-x-1" id="paginationControls">
            <!-- 分页控件将通过JS动态渲染 -->
          </div>
        </div>
      </div>

      <!-- 修改主内容区域中的饼图部分 -->
      <div class="mt-6 bg-white rounded-xl p-6 card-shadow">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">类别分布饼图</h3>
        <div class="bg-gray-50 p-4 rounded-lg" id="categoryPieChart">
          <!-- ECharts图表将通过JS动态渲染 -->
          <div class="text-center py-8 text-gray-500">
            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
            <p>加载中...</p>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>
<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
  <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
    <p>© 2025 商店进销存管理系统 - 版权所有</p>
  </div>
</footer>

<!-- 类别添加模态框 -->
<div id="categoryModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- 类别编辑模态框 -->
<div id="editCategoryModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>

<!-- JavaScript -->
<script>
  // 权限检查函数
  function hasPermission(permissionCode) {
    // 从localStorage或cookie中获取用户权限列表
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');
    return userPermissions.includes(permissionCode);
  }

  // 根据角色隐藏/展示按钮
  const applyRolePermissions = () => {
    fetch('/user-info')
            .then(response => {
              if (!response.ok) {
                throw new Error(`获取用户信息失败: 状态码 ${response.status}`);
              }
              return response.json(); // 解析JSON格式响应
            })
            .then(data => {
              console.log('用户信息响应:', data);

              // 检查响应结构是否正确
              if (data.code !== "200" || !data.data) {
                throw new Error(data.message || '响应数据格式错误');
              }

              const userData = data.data;
              const authorities = userData.authorities;

              // 使用正则表达式提取角色信息（假设authorities格式为"Roles:[ROLE_USER]"）
              const roles = authorities.match(/Roles:\[(.*?)\]/);
              if (roles) {
                const roleList = roles[1].split(","); // 注意：后端返回的是ROLE_USER，无空格，使用逗号直接分割
                console.log('用户角色:', roleList);

                // 存储用户权限到localStorage
                localStorage.setItem('userPermissions', JSON.stringify(roleList));

                if (!roleList.includes("ROLE_ADMIN")) {
                  // 隐藏管理员专属按钮
                  const addCategoryBtn = document.getElementById('addCategoryBtn');
                  if (addCategoryBtn) {
                    addCategoryBtn.style.display = 'none';
                  }

                  // 隐藏需要管理员权限的按钮
                  document.querySelectorAll('[data-permission]').forEach(button => {
                    const requiredPermission = button.getAttribute('data-permission');
                    if (!hasPermission(requiredPermission)) {
                      button.style.display = 'none';
                    }
                  });
                }
              } else {
                console.warn('未找到角色信息，原始数据:', authorities);
              }
            })
            .catch(error => {
              console.error('获取用户信息失败:', error);
              Toastify({
                text: '获取用户权限失败，请重新登录',
                duration: 3000,
                gravity: 'top',
                position: 'right',
                backgroundColor: '#f44336'
              }).showToast();
            });
  };

  // 确保在商品数据加载完成后再次应用权限
  const ensurePermissionsApplied = () => {
    // 如果数据是异步加载的，可能需要在数据加载完成后再次调用
    setTimeout(() => {
      applyRolePermissions();
    }, 500); // 等待500毫秒，确保数据加载完成
  };

  // 全局变量存储当前编辑的类别ID
  let currentEditingCategoryId = null;
  // 全局筛选参数
  let filterParams = {
    name: ''
  };
  // 存储所有类别数据
  let allCategories = [];
  // 全局ECharts实例
  let categoryChart = null;

  // 页面加载完成后初始化
  document.addEventListener('DOMContentLoaded', () => {
    initSidebarNavigation();
    setCurrentPageActive();

    // 延迟执行，确保所有资源都加载完成
    setTimeout(() => {
      loadCategories();
    }, 300); // 延迟300毫秒

    // 应用角色权限
    applyRolePermissions();

    // 确保数据加载完成后再次应用权限
    ensurePermissionsApplied();

    // 筛选按钮点击事件
    document.getElementById('filterBtn').addEventListener('click', () => {
      const filterForm = document.getElementById('filterForm');
      filterForm.classList.toggle('hidden');
    });

    // 应用筛选按钮点击事件
    document.getElementById('applyFilterBtn').addEventListener('click', applyFilter);

    // 重置筛选按钮点击事件
    document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

    // 绑定添加类别按钮事件
    document.getElementById('addCategoryBtn').addEventListener('click', showAddCategoryForm);

    // 绑定编辑商品按钮事件
    document.addEventListener('click', (e) => {
      // 处理编辑按钮
      if (e.target.closest('.edit-btn')) {
        const button = e.target.closest('.edit-btn');
        const categoryId = parseInt(button.getAttribute('data-id'));
        editCategory(categoryId);
      }

      // 处理删除按钮
      if (e.target.closest('.delete-btn')) {
        const button = e.target.closest('.delete-btn');
        const categoryId = parseInt(button.getAttribute('data-id'));
        deleteCategory(categoryId);
      }
    });
  });

  /**
   * 应用筛选条件
   */
  const applyFilter = () => {
    // 获取筛选表单的值
    filterParams = {
      name: document.getElementById('filterName').value.trim()
    };

    // 从第一页开始加载数据
    loadCategories(0);
  };

  /**
   * 重置筛选条件
   */
  const resetFilter = () => {
    // 重置表单
    document.getElementById('filterName').value = '';

    // 重置筛选参数
    filterParams = {
      name: ''
    };

    // 从第一页开始加载数据
    loadCategories(0);
  };

  /**
   * 从后端API加载类别数据（支持筛选）
   */
  let currentPage = 0; // 保存当前页码（后端从0开始）
  const loadCategories = (page = 0) => {
    const categoryTable = document.getElementById('categoryTable');
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationControls = document.getElementById('paginationControls');
    const categoryChartContainer = document.getElementById('categoryPieChart');

    // 显示加载中状态
    categoryTable.innerHTML = `
    <tr>
      <td colspan="4" class="py-4 text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        <p class="mt-2 text-gray-600">加载类别数据中...</p>
      </td>
    </tr>
  `;

    if (categoryChartContainer) {
      categoryChartContainer.innerHTML = `
      <div class="text-center py-8 text-gray-500">
        <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
        <p>加载中...</p>
      </div>
    `;
    }

    // 构建筛选参数
    const queryParams = new URLSearchParams({
      page: page,
      size: 10,
      ...(filterParams.name && { name: filterParams.name })
    });

    // 调用后端API获取类别数据
    fetch(`/category?${queryParams}`)
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('API响应数据:', apiResponse);
              categoryTable.innerHTML = '';

              // 验证响应结构
              if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                throw new Error(apiResponse?.message || 'API响应失败');
              }

              // 解构数据
              const { content: categories, totalElements, totalPages, pageable } = apiResponse.data;
              currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

              // 保存所有类别数据用于饼图
              allCategories = categories;

              // 更新分页信息
              const displayPage = currentPage + 1;
              paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
              updatePaginationControls(totalPages, displayPage);

              // 处理无数据情况
              if (categories.length === 0) {
                categoryTable.innerHTML = `
          <tr>
            <td colspan="4" class="py-4 text-center text-gray-500">没有找到符合条件的类别数据</td>
          </tr>
        `;

                if (categoryChartContainer) {
                  categoryChartContainer.innerHTML = `
            <div class="text-center py-8 text-gray-500">
              <i class="fa fa-folder-open-o text-4xl mb-4"></i>
              <p>暂无类别数据</p>
            </div>
          `;
                }
                return;
              }

              // 渲染类别数据
              categories.forEach(category => {
                const row = document.createElement('tr');
                row.className = 'border-b border-gray-100 hover:bg-gray-50';

                // 从API数据中提取字段（含默认值处理）
                const id = category.categoryId;
                const name = category.categoryName || '未知名称';
                const productCount = category.productCount !== null && category.productCount !== undefined ? category.productCount : 0;

                row.innerHTML = `
          <td class="py-3 text-sm text-gray-600">${id}</td>
          <td class="py-3 text-sm text-gray-600">${name}</td>
          <td class="py-3 text-sm text-gray-600">${productCount}</td>
          <td class="py-3 text-sm text-gray-600">
            <button data-id="${id}" class="edit-btn text-primary mr-2" data-permission="CATEGORY_EDIT">
              <i class="fa fa-pencil"></i> 编辑
            </button>
            <button data-id="${id}" class="delete-btn text-danger" data-permission="CATEGORY_DELETE">
              <i class="fa fa-trash"></i> 删除
            </button>
          </td>
        `;
                categoryTable.appendChild(row);
              });

              // 渲染ECharts饼图
              renderCategoryPieChart(allCategories);
            })
            .catch(error => {
              console.error('加载类别数据失败:', error);
              categoryTable.innerHTML = `
        <tr>
          <td colspan="4" class="py-4 text-center text-red-500">
            <i class="fa fa-exclamation-circle mr-2"></i> 加载类别数据失败，请稍后重试
          </td>
        </tr>
      `;

              if (categoryChartContainer) {
                categoryChartContainer.innerHTML = `
          <div class="text-center py-8 text-red-500">
            <i class="fa fa-exclamation-triangle text-4xl mb-4"></i>
            <p>加载类别图表失败</p>
          </div>
        `;
              }

              Toastify({
                text: `加载类别数据失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });

    // 确保重新应用角色权限
    setTimeout(() => {
      applyRolePermissions();
    }, 100); // 等待数据加载完成

  };

  /**
   * 更新分页控件
   */
  const updatePaginationControls = (totalPages, currentPage) => {
    const controls = document.getElementById('paginationControls');
    controls.innerHTML = '';

    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
    prevBtn.disabled = currentPage === 1;
    prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
    prevBtn.addEventListener('click', () => {
      if (currentPage > 1) {
        loadCategories(currentPage - 2); // 转换为后端页码（前端页码-1）
      }
    });
    controls.appendChild(prevBtn);

    // 页码按钮 (显示当前页及前后两页)
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
      const pageBtn = document.createElement('button');
      pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
      pageBtn.textContent = i;
      pageBtn.addEventListener('click', () => {
        loadCategories(i - 1); // 转换为后端页码（前端页码-1）
      });
      controls.appendChild(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
    nextBtn.addEventListener('click', () => {
      if (currentPage < totalPages) {
        loadCategories(currentPage); // 转换为后端页码（前端页码-1）
      }
    });
    controls.appendChild(nextBtn);
  };

  /**
   * 渲染ECharts类别饼图
   */
  const renderCategoryPieChart = (categories) => {
    const chartContainer = document.getElementById('categoryPieChart');
    if (!chartContainer) return;

    // 隐藏加载状态，创建图表容器
    chartContainer.innerHTML = `
    <div class="echart-container" id="categoryEChart"></div>
  `;

    // 处理无数据情况
    if (!categories || categories.length === 0) {
      chartContainer.innerHTML = `
      <div class="text-center py-8 text-gray-500">
        <i class="fa fa-folder-open-o text-4xl mb-4"></i>
        <p>暂无类别数据</p>
      </div>
    `;
      return;
    }

    // 准备图表数据
    const chartData = prepareChartData(categories);

    // 销毁已存在的图表实例（如果有）
    if (categoryChart) {
      categoryChart.dispose();
    }

    // 创建ECharts实例
    categoryChart = echarts.init(document.getElementById('categoryEChart'));

    // 配置项 - 饼图
    const option = {
      title: {
        text: '类别商品分布',
        subtext: `共 ${chartData.total} 个商品`,
        left: 'center',
        top: 10,
        textStyle: {
          color: '#333'
        },
        subtextStyle: {
          color: '#666',
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'middle',
        data: chartData.labels,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          color: '#666',
          fontSize: 12
        }
      },
      series: [{
        name: '商品数量',
        type: 'pie',
        radius: ['40%', '75%'], // 环形饼图
        center: ['50%', '50%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        labelLine: {
          show: true
        },
        data: chartData.data.map((item, index) => ({
          name: item.name,
          value: item.value,
          itemStyle: {
            color: getEChartsColor(index) // 自定义颜色方案
          }
        }))
      }]
    };

    // 渲染图表
    categoryChart.setOption(option);

    // 窗口大小改变时重绘图表
    window.addEventListener('resize', () => {
      if (categoryChart) {
        categoryChart.resize();
      }
    });
  };

  /**
   * 准备ECharts图表数据
   */
  const prepareChartData = (categories) => {
    const data = [];
    let total = 0;

    categories.forEach((category, index) => {
      const name = category.categoryName || `类别${index + 1}`;
      const value = category.productCount !== null && category.productCount !== undefined
              ? category.productCount : 0;
      data.push({ name, value });
      total += value;
    });

    return {
      data,
      labels: data.map(item => item.name),
      total
    };
  };

  /**
   * 自定义ECharts颜色方案
   */
  const getEChartsColor = (index) => {
    const colors = [
      '#165DFF', '#0FC6C2', '#00B42A',
      '#FF7D00', '#F53F3F', '#86909C',
      '#9D75FF', '#FF6B9D', '#70C1B3',
      '#F7BA1E', '#577590', '#F59E0B',
      '#10B981', '#3B82F6', '#8B5CF6', '#EC4899'
    ];
    return colors[index % colors.length];
  };

  /**
   * 显示添加类别表单
   */
  const showAddCategoryForm = () => {
    const modal = document.getElementById('categoryModal');
    modal.classList.remove('hidden');

    const formContainer = document.createElement('div');
    formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
    formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">添加新类别</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('categoryModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <form id="addCategoryForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="categoryName">类别名称</label>
        <input type="text" id="categoryName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入类别名称">
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('categoryModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">添加类别</button>
      </div>
    </form>
  `;

    modal.innerHTML = '';
    modal.appendChild(formContainer);

    // 表单提交事件
    document.getElementById('addCategoryForm').addEventListener('submit', (e) => {
      e.preventDefault();
      addCategory();
    });
  };

  /**
   * 添加类别到系统
   */
  const addCategory = () => {
    // 获取表单数据
    const formData = {
      categoryName: document.getElementById('categoryName').value
    };

    // 验证表单
    if (!formData.categoryName) {
      Toastify({
        text: "请输入类别名称",
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      return;
    }

    // 显示加载状态
    const submitButton = document.querySelector('#addCategoryForm button[type="submit"]');
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

    // 调用API
    fetch('/category', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('添加类别API响应:', apiResponse);

              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '添加类别';

              // 处理响应
              if (apiResponse) {
                Toastify({
                  text: "类别添加成功",
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#4CAF50",
                }).showToast();
                // 关闭表单
                document.getElementById('categoryModal').classList.add('hidden');
                // 刷新类别列表
                loadCategories();
              } else {
                const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '添加失败：未知错误';
                Toastify({
                  text: errorMsg,
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#f44336",
                }).showToast();
              }
            })
            .catch(error => {
              console.error('添加类别失败:', error);
              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '添加类别';
              // 显示错误信息
              Toastify({
                text: `添加类别失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });
  };

  /**
   * 加载指定类别详情
   */
  const fetchCategoryDetails = async (categoryId) => {
    try {
      const response = await fetch(`/category/${categoryId}`);
      if (!response.ok) {
        throw new Error(`获取类别详情失败: 状态码 ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('获取类别详情失败:', error);
      Toastify({
        text: `获取类别详情失败: ${error.message}`,
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      throw error;
    }
  };

  /**
   * 显示编辑类别表单
   */
  const showEditCategoryForm = (categoryId) => {
    currentEditingCategoryId = categoryId;
    const modal = document.getElementById('editCategoryModal');
    modal.classList.remove('hidden');

    const formContainer = document.createElement('div');
    formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
    formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">编辑类别</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('editCategoryModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="animate-pulse mb-4">
      <div class="h-6 bg-gray-200 rounded w-full mb-2"></div>
      <div class="h-6 bg-gray-200 rounded w-3/4"></div>
    </div>
    <form id="editCategoryForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editCategoryName">类别名称</label>
        <input type="text" id="editCategoryName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入类别名称">
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('editCategoryModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">保存修改</button>
      </div>
    </form>
  `;

    modal.innerHTML = '';
    modal.appendChild(formContainer);

    // 加载类别详情
    fetchCategoryDetails(categoryId)
            .then(apiResponse => {
              if (apiResponse && apiResponse.code === "200" && apiResponse.data) {
                const category = apiResponse.data;
                document.getElementById('editCategoryName').value = category.categoryName || '';

                // 移除加载动画
                const loadingPlaceholder = modal.querySelector('.animate-pulse');
                if (loadingPlaceholder) {
                  loadingPlaceholder.remove();
                }
              } else {
                const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '获取类别详情失败：未知错误';
                Toastify({
                  text: errorMsg,
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#f44336",
                }).showToast();

                // 关闭模态框
                setTimeout(() => {
                  modal.classList.add('hidden');
                }, 1500);
              }
            })
            .catch(error => {
              // 关闭模态框
              modal.classList.add('hidden');
            });

    // 表单提交事件
    document.getElementById('editCategoryForm').addEventListener('submit', (e) => {
      e.preventDefault();
      updateCategory();
    });
  };

  /**
   * 编辑类别
   */
  const editCategory = (categoryId) => {
    showEditCategoryForm(categoryId);
  };

  /**
   * 更新类别信息
   */
  const updateCategory = () => {
    if (!currentEditingCategoryId) {
      Toastify({
        text: "未选择要编辑的类别",
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      return;
    }

    // 获取表单数据
    const formData = {
      categoryName: document.getElementById('editCategoryName').value
    };

    // 验证表单
    if (!formData.categoryName) {
      Toastify({
        text: "请输入类别名称",
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      return;
    }

    // 显示加载状态
    const submitButton = document.querySelector('#editCategoryForm button[type="submit"]');
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

    // 调用API
    fetch(`/category/${currentEditingCategoryId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('更新类别API响应:', apiResponse);

              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '保存修改';

              // 处理响应
              if (apiResponse) {
                Toastify({
                  text: "类别更新成功",
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#4CAF50",
                }).showToast();
                // 关闭表单
                document.getElementById('editCategoryModal').classList.add('hidden');
                // 刷新类别列表
                loadCategories();
              } else {
                const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '更新失败：未知错误';
                Toastify({
                  text: errorMsg,
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#f44336",
                }).showToast();
              }
            })
            .catch(error => {
              console.error('更新类别失败:', error);
              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '保存修改';
              // 显示错误信息
              Toastify({
                text: `更新类别失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });
  };

  /**
   * 删除类别
   */
  const deleteCategory = (categoryId) => {
    // 确认对话框
    if (!confirm("确定要删除此类别吗？删除后将无法恢复。")) {
      return;
    }

    // 显示加载状态
    const deleteButtons = document.querySelectorAll(`button[onclick="deleteCategory(${categoryId})"]`);
    deleteButtons.forEach(btn => {
      btn.disabled = true;
      btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 删除中...';
    });

    // 调用API
    fetch(`/category/${categoryId}`, {
      method: 'DELETE',
    })
            .then(response => {
              if (response.ok) {
                Toastify({
                  text: "类别删除成功",
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#4CAF50",
                }).showToast();
              //刷新列表
                loadCategories();
              } else {
                throw new Error(`删除失败: ${response.statusText}`);
              }
            })
            .then(apiResponse => {
              console.log('删除类别API响应:', apiResponse);
              // 恢复按钮状态
              deleteButtons.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fa fa-trash"></i> 删除';
              });
            })
            .catch(error => {
              console.error('删除类别失败:', error);
              // 恢复按钮状态
              deleteButtons.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fa fa-trash"></i> 删除';
              });
              // 显示错误信息
              Toastify({
                text: `删除类别失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });
  };

  /**
   * 初始化侧边栏导航
   */
  const initSidebarNavigation = () => {
    const sidebarItems = document.querySelectorAll('.sidebar-item');

    sidebarItems.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();

        const path = item.getAttribute('data-path');
        if (!path) return;

        // 更新激活状态
        updateActiveItem(item);

        // 显示加载指示器
        showPageLoader();

        // 使用平滑过渡加载新页面
        setTimeout(() => {
          window.location.href = path;
        }, 300); // 动画持续时间
      });
    });
  };

  /**
   * 更新激活菜单项
   */
  const updateActiveItem = (activeItem) => {
    document.querySelectorAll('.sidebar-item').forEach(item => {
      item.classList.remove('active');
    });
    activeItem.classList.add('active');
  };

  /**
   * 设置当前页面菜单项为激活状态
   */
  const setCurrentPageActive = () => {
    const currentPath = window.location.pathname;
    const sidebarItems = document.querySelectorAll('.sidebar-item');

    sidebarItems.forEach(item => {
      const itemPath = item.getAttribute('data-path');
      if (itemPath && currentPath.endsWith(itemPath)) {
        updateActiveItem(item);
        return;
      }
    });
  };

  /**
   * 显示页面加载指示器
   */
  const showPageLoader = () => {
    const mainContent = document.querySelector('main');

    // 创建加载指示器元素
    const loader = document.createElement('div');
    loader.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50 transition-opacity duration-300';
    loader.innerHTML = `
    <div class="text-center">
      <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      <p class="mt-4 text-gray-600">加载中...</p>
    </div>
  `;

    // 添加到页面
    document.body.appendChild(loader);

    // 300ms后移除（与导航延迟匹配）
    setTimeout(() => {
      loader.classList.add('opacity-0');
      setTimeout(() => {
        document.body.removeChild(loader);
      }, 300);
    }, 300);
  };

  /**
   * 页面卸载时销毁图表实例，释放资源
   */
  window.addEventListener('beforeunload', () => {
    if (categoryChart) {
      categoryChart.dispose();
      categoryChart = null;
    }
  });
</script>
</body>

</html>